package com.june.p2p;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer {

	private static final String QUEUE_NAME = "testQueue";

	public static void main(String[] args) {

		// 创建一个 ConnectionFactory
		// user/password/url: admin/admin/tcp://localhost:61616
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnectionFactory.DEFAULT_USER, 
				ActiveMQConnectionFactory.DEFAULT_PASSWORD, 
				ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
		MessageConsumer consumer = null;
		Session session = null;
		Connection connection = null;
		try {
			// 从连接工厂得到一个连接 QueueConnection
			connection = connectionFactory.createConnection();
			// 开启连接
			connection.start();
			
			// 通过连接来建立一个会话
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			// 创建消息队列
			Queue queue = session.createQueue(QUEUE_NAME);
			// 创建消息消费者
			consumer = session.createConsumer(queue);
			
			// 添加消息监听器进行异步接收消息
			consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message) {
					if (!(message instanceof TextMessage)) {
						System.out.println("消息类型不正确，不予处理");
						return;
					}
					TextMessage textMessage = (TextMessage) message;
					if (textMessage != null) {
						try {
							System.out.println("从消息队列接收到的消息: " + textMessage.getText());
						} catch (JMSException e) {
							e.printStackTrace();
						}
					}
				}
			});
			
			// 同步接收消息
//			while (true) {			
//				TextMessage message = (TextMessage) consumer.receive();
//				if (message != null) {				
//					System.out.println("从消息队列接收到的消息: " + message.getText());
//				} else {
//					System.out.println("接收消息完毕！");
//					break;
//				}
//			}
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {			
			try {
				if (consumer != null) {					
					consumer.close();
				}
				if (session != null) {					
					session.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
